package com.szholly.pro.watergas_server.ps.android.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;

import com.szholly.pro.watergas_server.ps.android.bean.QcTaskParam;
import com.szholly.pro.watergas_server.ps.android.bean.QcTaskTypeRow;
import com.szholly.pro.watergas_server.ps.android.common.DateTime;
import com.szholly.pro.watergas_server.ps.android.common.ResultUtils;
import com.szholly.pro.watergas_server.ps.android.common.SqlUtils;
import com.szholly.pro.watergas_server.ps.android.common.TableRowMap;
import com.szholly.pro.watergas_server.ps.android.common.ValidUtils;
import com.szholly.pro.watergas_server.ps.android.service.QcBlindOperationService;
import com.szholly.pro.watergas_server.ps.android.service.QcLabOperationService;
import com.szholly.pro.watergas_server.ps.android.service.QcOperationService;
import com.szholly.pro.watergas_server.ps.android.service.QcOperationServiceImpl;
import com.szholly.pro.watergas_server.ps.android.service.QcTaskBlindSpotStrategy;
import com.szholly.pro.watergas_server.ps.android.service.QcTaskBuildBlindSpotStrategy;
import com.szholly.pro.watergas_server.ps.android.service.QcTaskDataContrastStrategy;
import com.szholly.pro.watergas_server.ps.android.service.QcTaskLabStrategy;
import com.szholly.pro.watergas_server.ps.android.service.QcTaskLocaleCheckStrategy;
import com.szholly.pro.watergas_server.ps.android.service.QcTaskSampleStrategy;
import com.szholly.pro.watergas_server.ps.android.service.QcTaskStrategy;
import com.szholly.pro.watergas_server.ps.data.QcBatchRow;
import com.szholly.pro.watergas_server.ps.data.QcBatchTable;
import com.szholly.pro.watergas_server.ps.data.SystemOperationLogRow;
import com.szholly.pro.watergas_server.ps.data.SystemOperationLogTable;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONObject;

/**
 * 质控任务控制器
 * 
 * 2017/6/16 <br/>
 *
 * @author Joey Huang QQ:273179370）
 */
@Controller
@RequestMapping("/android/qc/task/*")
public class QcTaskControl implements ServletContextAware {
	@SuppressWarnings("unused")
	private ServletContext servletContext;

	private Map<String, QcTaskStrategy> mStrategyMap;

	@Override
	public void setServletContext(ServletContext arg0) {
		this.servletContext = arg0;
		QcOperationService normalService = new QcOperationServiceImpl();
		QcOperationService blindService = new QcBlindOperationService();
		QcOperationService labService = new QcLabOperationService();

		mStrategyMap = new HashMap<>();
		mStrategyMap.put(QcControl.SAMPLE.getId(), new QcTaskSampleStrategy(normalService));
		mStrategyMap.put(QcControl.LAB.getId(), new QcTaskLabStrategy(labService));
		mStrategyMap.put(QcControl.DATA_CONTRAST.getId(), new QcTaskDataContrastStrategy(normalService));

		mStrategyMap.put(QcControl.BLIND.getId(), new QcTaskBlindSpotStrategy(blindService));
		mStrategyMap.put(QcControl.SPOT.getId(), new QcTaskBlindSpotStrategy(blindService));
		mStrategyMap.put(QcControl.BUILD_BLIND.getId(), new QcTaskBuildBlindSpotStrategy(normalService));
		mStrategyMap.put(QcControl.BUILD_SPOT.getId(), new QcTaskBuildBlindSpotStrategy(normalService));

		mStrategyMap.put(QcControl.LOCACLE_CHECK_LAB.getId(), new QcTaskLocaleCheckStrategy(normalService));
		mStrategyMap.put(QcControl.LOCACLE_CHECK_SAMPLE.getId(), new QcTaskLocaleCheckStrategy(normalService));
		mStrategyMap.put(QcControl.LOCACLE_CHECK_OPERATION.getId(), new QcTaskLocaleCheckStrategy(normalService));
	}

	/**
	 * 添加任务
	 */
	@RequestMapping("/addOperationTask")
	@ResponseBody
	public String addOperationTask(String token, String userId, String companyCode, String pointCode, String taskTypeCode, String taskCode,
			String parentTaskCode, String data) {
		try {
			ValidUtils.validateToken(token);
			ValidUtils.hasText(userId, "用户编号为空");
			ValidUtils.hasText(taskTypeCode, "任务类型编号为空");
			QcTaskStrategy taskStrategy = mStrategyMap.get(taskTypeCode);
			QcTaskParam taskParam = new QcTaskParam();
			taskParam.setUserId(userId);
			taskParam.setTaskTypeCode(taskTypeCode);
			taskParam.setCompanyCode(companyCode);
			taskParam.setPointCode(pointCode);
			taskParam.setParentTaskCode(parentTaskCode);
			taskParam.setTaskCode(taskCode);
			taskParam.setData(data);
			RowBase task = taskStrategy.addTask(taskParam);
			return ResultUtils.getToastResult(task);
		} catch (Exception e) {
			String message = e == null ? null : e.getMessage();
			if (message != null) {
				return ResultUtils.getToastResult(message + ",任务添加失败");
			} else {
				return ResultUtils.getToastResult("任务添加失败");
			}
		}
	}

	/**
	 * 添加任务
	 */
	@RequestMapping("/deleteOperationTask")
	@ResponseBody
	public String deleteOperationTask(String token, String userId, String companyCode, String pointCode, String taskTypeCode, String taskCode,
			String parentTaskCode, String data) {
		try {
			ValidUtils.validateToken(token);
			ValidUtils.hasText(userId, "用户编号为空");
			ValidUtils.hasText(taskTypeCode, "任务类型编号为空");
			ValidUtils.hasText(taskCode, "任务编号为空");
			QcTaskStrategy taskStrategy = mStrategyMap.get(taskTypeCode);
			QcTaskParam taskParam = new QcTaskParam();
			taskParam.setUserId(userId);
			taskParam.setTaskTypeCode(taskTypeCode);
			taskParam.setCompanyCode(companyCode);
			taskParam.setPointCode(pointCode);
			taskParam.setParentTaskCode(parentTaskCode);
			taskParam.setTaskCode(taskCode);
			taskParam.setData(data);

			taskStrategy.deleteTask(taskParam);
			return ResultUtils.getToastResult("删除成功", true);
		} catch (Exception e) {
			String message = e == null ? null : e.getMessage();
			if (message != null) {
				return ResultUtils.getToastResult(message + ",任务数据获取失败");
			} else {
				return ResultUtils.getToastResult("任务数据获取失败");
			}
		}
	}

	/**
	 * 添加任务
	 */
	@RequestMapping("/deleteOperationTaskAndContent")
	@ResponseBody
	public String deleteOperationTaskAndContent(String token, String userId, String companyCode, String pointCode, String taskTypeCode,
			String taskCode, String parentTaskCode, String data) {
		try {
			ValidUtils.validateToken(token);
			ValidUtils.hasText(userId, "用户编号为空");
			ValidUtils.hasText(taskTypeCode, "任务类型编号为空");
			ValidUtils.hasText(taskCode, "任务编号为空");
			QcTaskStrategy taskStrategy = mStrategyMap.get(taskTypeCode);
			QcTaskParam taskParam = new QcTaskParam();
			taskParam.setUserId(userId);
			taskParam.setTaskTypeCode(taskTypeCode);
			taskParam.setCompanyCode(companyCode);
			taskParam.setPointCode(pointCode);
			taskParam.setParentTaskCode(parentTaskCode);
			taskParam.setTaskCode(taskCode);
			taskParam.setData(data);
			taskStrategy.deleteProcessedTask(taskParam);

			try {// 保存日志
				QcTaskTypeRow taskTypeRow = QcControl.getTaskTypeRow(taskTypeCode);
				StringBuilder desBuild = new StringBuilder();
				desBuild.append("删除  ");
				desBuild.append("运维单号:" + taskCode + "  ");
				if (!StringUtils.IsNullOrSpace(companyCode)) {
					desBuild.append("公司:" + companyCode + "  ");
				}
				if (!StringUtils.IsNullOrSpace(pointCode)) {
					desBuild.append("站点:" + pointCode + "  ");
				}
				desBuild.append("任务名称:" + taskTypeRow.getName());
				TableRowMap tableRow = new TableRowMap(SystemOperationLogTable.TABLE_NAME);
				tableRow.put(SystemOperationLogRow.FIELD_OperateTime, new DateTime().toString());
				tableRow.put(SystemOperationLogRow.FIELD_OperateItem, desBuild.toString());
				tableRow.put(SystemOperationLogRow.FIELD_Operator, userId);
				tableRow.put(SystemOperationLogRow.FIELD_ModuleType, "15");
				SqlUtils.insert(tableRow);
			} catch (Exception e) {
			}

			return ResultUtils.getToastResult("删除成功", true);
		} catch (Exception e) {
			String message = e == null ? null : e.getMessage();
			if (message != null) {
				return ResultUtils.getToastResult(message + ",任务数据获取失败");
			} else {
				return ResultUtils.getToastResult("任务数据获取失败");
			}
		}
	}

	/**
	 * 获取任务列表
	 */
	@RequestMapping("/getOperationTaskListData")
	@ResponseBody
	public String getOperationTaskListData(String token, String userId, String companyCode, String pointCode, String taskTypeCode, String taskCode,
			String parentTaskCode, String data) {
		try {
			ValidUtils.validateToken(token);
			ValidUtils.hasText(userId, "用户编号为空");
			ValidUtils.hasText(taskTypeCode, "任务类型编号为空");
			QcTaskStrategy taskStrategy = mStrategyMap.get(taskTypeCode);
			QcTaskParam taskParam = new QcTaskParam();
			taskParam.setUserId(userId);
			taskParam.setTaskTypeCode(taskTypeCode);
			taskParam.setCompanyCode(companyCode);
			taskParam.setPointCode(pointCode);
			taskParam.setParentTaskCode(parentTaskCode);
			taskParam.setTaskCode(taskCode);
			taskParam.setData(data);
			List<RowBase> taskList = taskStrategy.getTaskList(taskParam);
			return ResultUtils.getToastResult(taskList);
		} catch (Exception e) {
			String message = e == null ? null : e.getMessage();
			if (message != null) {
				return ResultUtils.getToastResult(message + ",任务数据获取失败");
			} else {
				return ResultUtils.getToastResult("任务数据获取失败");
			}
		}
	}

	/**
	 * 获取任务初始化
	 */
	@RequestMapping("/getOperationTaskInitData")
	@ResponseBody
	public String getOperationTaskInitData(String token, String userId, String companyCode, String pointCode, String taskTypeCode, String taskCode,
			String parentTaskCode, String data) {
		try {
			ValidUtils.validateToken(token);
			ValidUtils.hasText(userId, "用户编号为空");
			ValidUtils.hasText(taskTypeCode, "任务类型编号为空");
			ValidUtils.hasText(taskCode, "任务编号为空");

			QcTaskStrategy taskStrategy = mStrategyMap.get(taskTypeCode);
			QcTaskParam taskParam = new QcTaskParam();
			taskParam.setUserId(userId);
			taskParam.setTaskTypeCode(taskTypeCode);
			taskParam.setCompanyCode(companyCode);
			taskParam.setPointCode(pointCode);
			taskParam.setParentTaskCode(parentTaskCode);
			taskParam.setTaskCode(taskCode);
			taskParam.setData(data);
			RowBase initData = taskStrategy.getTaskInitData(taskParam);
			return ResultUtils.getToastResult(initData);
		} catch (Exception e) {
			String message = e == null ? null : e.getMessage();
			if (message != null) {
				return ResultUtils.getToastResult(message + ",任务初始化数据获取失败");
			} else {
				return ResultUtils.getToastResult("任务初始化数据获取失败");
			}
		}
	}

	/**
	 * 获取运维任务详情数据
	 */
	@RequestMapping("/getOperationTaskDetailData")
	@ResponseBody
	public String getOperationTaskDetailData(String token, String userId, String companyCode, String pointCode, String taskTypeCode, String taskCode,
			String parentTaskCode, String data) {
		try {
			ValidUtils.validateToken(token);
			ValidUtils.hasText(userId, "用户编号为空");
			ValidUtils.hasText(taskTypeCode, "任务类型编号为空");
			ValidUtils.hasText(taskCode, "任务编号为空");

			QcTaskStrategy taskStrategy = mStrategyMap.get(taskTypeCode);
			QcTaskParam taskParam = new QcTaskParam();
			taskParam.setUserId(userId);
			taskParam.setTaskTypeCode(taskTypeCode);
			taskParam.setCompanyCode(companyCode);
			taskParam.setPointCode(pointCode);
			taskParam.setParentTaskCode(parentTaskCode);
			taskParam.setTaskCode(taskCode);
			taskParam.setData(data);
			RowBase detailData = taskStrategy.getProcessedTaskInitData(taskParam);
			return ResultUtils.getToastResult(detailData);
		} catch (Exception e) {
			String message = e == null ? null : e.getMessage();
			if (message != null) {
				return ResultUtils.getToastResult(message + ",任务详情数据获取失败");
			} else {
				return ResultUtils.getToastResult("任务详情数据获取失败");
			}
		}
	}

	/**
	 * 保存任务
	 */
	@RequestMapping("/saveOperationTask")
	@ResponseBody
	public String saveOperationTask(String token, String userId, String companyCode, String pointCode, String taskTypeCode, String taskCode,
			String parentTaskCode, String data) {
		try {
			ValidUtils.validateToken(token);
			ValidUtils.hasText(userId, "用户编号为空");
			ValidUtils.hasText(taskTypeCode, "任务类型编号为空");

			QcTaskStrategy taskStrategy = mStrategyMap.get(taskTypeCode);
			QcTaskParam taskParam = new QcTaskParam();
			taskParam.setUserId(userId);
			taskParam.setTaskTypeCode(taskTypeCode);
			taskParam.setCompanyCode(companyCode);
			taskParam.setPointCode(pointCode);
			taskParam.setParentTaskCode(parentTaskCode);
			taskParam.setTaskCode(taskCode);
			taskParam.setData(data);
			taskStrategy.saveTask(taskParam);
			return ResultUtils.getToastResult("保存成功", true);
		} catch (Exception e) {
			String message = e == null ? null : e.getMessage();
			if (message != null) {
				return ResultUtils.getToastResult(message + ",保存失败");
			} else {
				return ResultUtils.getToastResult("保存失败");
			}
		}
	}

	/**
	 * 编辑任务
	 */
	@RequestMapping("/updateOperationTask")
	@ResponseBody
	public String updateOperationTask(String token, String userId, String companyCode, String pointCode, String taskTypeCode, String taskCode,
			String parentTaskCode, String data) {
		try {
			ValidUtils.validateToken(token);
			ValidUtils.hasText(userId, "用户编号为空");
			ValidUtils.hasText(taskTypeCode, "任务类型编号为空");

			QcTaskStrategy taskStrategy = mStrategyMap.get(taskTypeCode);
			QcTaskParam taskParam = new QcTaskParam();
			taskParam.setUserId(userId);
			taskParam.setTaskTypeCode(taskTypeCode);
			taskParam.setCompanyCode(companyCode);
			taskParam.setPointCode(pointCode);
			taskParam.setParentTaskCode(parentTaskCode);
			taskParam.setTaskCode(taskCode);
			taskParam.setData(data);
			taskStrategy.updateTask(taskParam);
			return ResultUtils.getToastResult("编辑成功", true);
		} catch (Exception e) {
			String message = e == null ? null : e.getMessage();
			if (message != null) {
				return ResultUtils.getToastResult(message + ",编辑失败");
			} else {
				return ResultUtils.getToastResult("编辑失败");
			}
		}
	}

	/**
	 * 编辑任务
	 */
	@RequestMapping("/updateOnlyOperationTask")
	@ResponseBody
	public String updateOnlyOperationTask(String token, String userId, String companyCode, String pointCode, String taskTypeCode, String taskCode,
			String data) {
		try {
			ValidUtils.validateToken(token);
			ValidUtils.hasText(userId, "用户编号为空");
			ValidUtils.hasText(taskTypeCode, "任务类型编号为空");
			JSONObject taskObject = JSONObject.fromObject(data);
			TableRowMap tableRowMap = TableRowMap.get(taskObject, QcBatchTable.TABLE_NAME);
			String status = (String) tableRowMap.get(QcBatchRow.FIELD_Status);
			String batchCode = (String) tableRowMap.get(QcBatchRow.FIELD_Id);

			if ("2".equals(status)) {// 设置为已分析的前提是所有的实验都已经完成分析
				makeSureLabAllFinish(batchCode);
			}

			SqlUtils.update(tableRowMap, new String[] { QcBatchRow.FIELD_Id });
			return ResultUtils.getToastResult("编辑成功", true);
		} catch (Exception e) {
			String message = e == null ? null : e.getMessage();
			if (message != null) {
				return ResultUtils.getToastResult(message);
			} else {
				return ResultUtils.getToastResult("编辑失败");
			}
		}
	}

	private void makeSureLabAllFinish(String batchCode) throws Exception {
		ValidUtils.hasText(batchCode);
		List<GlobalParameter>parms = new ArrayList<>();
		parms.add(new GlobalParameter("batchCode", batchCode));
		parms.add(new GlobalParameter("jobCode", QcControl.LAB.getJobId()));
		String sql = "select t.task_code\n"
				+ "  from OP_TASK t\n"
				+ " where t.task_status <> 2\n"
				+ "   and t.job_id = @jobCode\n"
				+ "   and t.parent_task_code = @batchCode";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		ValidUtils.isTrue(CollectionUtils.isEmpty(rows), "尚有实验未完成");
	}
}
